<template>
  <div class="row ant-bg">
    <div class="col-6">
      <el-form
        class="col-left container-fluid"
        label-width="0px"
        :model="formInline"
        size="default"
      >
        <el-form-item class="row" :style="{ height: '42px' }">
          <el-input
            class="input m-mr-4"
            v-model.lazy="formInline.name"
            placeholder="输入题目名或ID搜索"
          ></el-input>
          <div class="input">
            <el-cascader
              placeholder="输入知识点进行搜索"
              v-model="setlabel"
              :style="{ width: '100%' }"
              :options="grouplabel"
              filterable
              :props="{
                checkStrictly: true,
                value: 'ID',
                label: 'name',
                expandTrigger: 'hover',
              }"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item :style="{ height: '42px' }">
          <el-button-group v-model="formInline.range" size="default">
            <el-button
              :type="formInline.range === 'public' ? 'primary' : ''"
              value="public"
              @click="formInline.range = 'public'"
              >公开题目</el-button
            >
            <el-button
              v-if="tenant_id"
              :type="formInline.range === 'accoder' ? 'primary' : ''"
              value="accoder"
              @click="formInline.range = 'accoder'"
              >Accoder</el-button
            >
            <el-button
              :type="formInline.range === 'team' ? 'primary' : ''"
              value="team"
              @click="formInline.range = 'team'"
              >团队题目</el-button
            >
            <el-button
              :type="formInline.range === 'user' ? 'primary' : ''"
              value="user"
              @click="formInline.range = 'user'"
              >我的题目</el-button
            >
          </el-button-group>
        </el-form-item>

        <div class="row">
          <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
            编号
          </div>
          <div class="col" :style="{ height: '42px', lineHeight: '42px' }">
            名称
          </div>
          <div
            :style="{
              width: '50px',
              padding: 0,
              height: '42px',
              lineHeight: '42px',
            }"
          ></div>
          <div
            :style="{
              width: '90px',
              padding: 0,
              height: '42px',
              lineHeight: '42px',
            }"
          >
            添加到专题
          </div>
        </div>
        <hr :style="{ marginTop: '6px', marginBottom: '6px' }" />
        <div class="mydata">
          <div
            class="row list"
            v-for="v in getquestion"
            :key="v.ID"
            :style="{ marginTop: '6px', marginBottom: '6px' }"
            :class="
              !!questionid.find((c) => c.ID === v.ID) ? 'text-black-50' : ''
            "
          >
            <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
              {{ v.ID }}
            </div>
            <div
              class="col text-truncate"
              :style="{ height: '42px', lineHeight: '42px' }"
            >
              {{ v.name }}
              <span :style="{ fontSize: '12px', color: '#888' }">{{
                v.goldremarks
              }}</span>
            </div>
            <!-- <router-link :to="{ name: '题目',  params: { ID: v.ID },  }" target="_blank" class="router-link-q">
                            预览
                        </router-link> -->
            <div
              class="text-center"
              :style="{
                width: '90px',
                padding: 0,
                height: '42px',
                lineHeight: '42px',
              }"
            >
              <span
                class="cu"
                :style="{
                  width: '24px',
                  height: '24px',
                  background: 'var(--color-cheng)',
                  borderRadius: '2px',
                  display: 'inline-block',
                  lineHeight: '24px',
                }"
                @click="addclick(v)"
              >
                <el-icon
                  color="#fff"
                  size="18px"
                  :style="{ transform: 'translateY(3px)' }"
                >
                  <Plus />
                </el-icon>
              </span>
            </div>
          </div>
        </div>
        <el-pagination
          class="pager"
          :page-size="limit"
          :total="getquestioncount"
          @current-change="currentchange"
          layout="total,prev, pager, next"
          :current-page="Math.floor(Number(formInline._offset) / limit) + 1"
        ></el-pagination>
      </el-form>
    </div>
    <div class="col-6">
      <el-form
        class="col-right container-fluid"
        label-width="0px"
        :model="formInline"
      >
        <div class="row" :style="{ height: '42px', lineHeight: '42px' }">
          <div class="col">
            <strong>已添加题目</strong>
          </div>
          <div class="col text-right">
            <strong>
              已添加：
              <span :style="{ color: 'var(--color-cheng)' }">{{
                questionid.length
              }}</span>
              题
            </strong>
          </div>
        </div>
        <el-form-item :style="{ height: '42px' }"
          >可拖拽题目改变顺序排列</el-form-item
        >
        <div class="row">
          <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
            编号
          </div>
          <div class="col" :style="{ height: '42px', lineHeight: '42px' }">
            名称
          </div>
          <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
            题型
          </div>
          <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
            删除
          </div>
        </div>
        <hr :style="{ marginTop: '6px', marginBottom: '6px' }" />
        <draggable
          v-model="question"
          group="people"
          @start="drag = true"
          @end="drag = true"
          item-key="ID"
          class="mydata"
          chosenClass="chosen"
        >
          <template #item="{ element, index }">
            <div
              class="row"
              :style="{
                marginTop: '6px',
                marginBottom: '6px',
                cursor: 'all-scroll',
              }"
            >
              <div
                :style="{ width: '80px', height: '42px', lineHeight: '42px' }"
              >
                {{ element[p.index ? p.index : "ID"] }}
              </div>
              <div
                class="col text-truncate"
                :style="{ height: '42px', lineHeight: '42px' }"
              >
                {{ element.name }}
                <span :style="{ fontSize: '12px', color: '#888' }">{{
                  element.goldremarks
                }}</span>
              </div>
              <div
                :style="{ width: '80px', height: '42px', lineHeight: '42px' }"
              >
                {{ element.type }}
              </div>
              <div
                class="text-center"
                :style="{ width: '80px', height: '42px', lineHeight: '42px' }"
              >
                <span
                  class="cu"
                  :style="{
                    width: '24px',
                    height: '24px',
                    background: 'var(--color-cheng)',
                    borderRadius: '2px',
                    display: 'inline-block',
                    lineHeight: '24px',
                  }"
                  @click="removeclick(index)"
                >
                  <el-icon
                    color="#fff"
                    size="18px"
                    :style="{ transform: 'translateY(3px)' }"
                  >
                    <semi-select />
                  </el-icon>
                </span>
              </div>
            </div>
          </template>
        </draggable>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Plus, SemiSelect } from "@element-plus/icons-vue";
import { debounce, flatten } from "underscore";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import draggable from "vuedraggable";
import { useStore } from "vuex";
import { Iobj } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { findpid } from "../../../util/code";

// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);

const store = useStore(Storekey);
const user = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});
const teamId = computed(() => {
  return user.value?.teamid;
});
const getteam = computed(() => {
  return store.state.team?.rows || [];
});
const getlabel = computed(() => {
  return store.state.label?.rows || [];
});

const p = defineProps<{
  removeclick: (i: number) => void;
  questionid: Studycodemodel.Iquestion[];
  addclick: Function;
  _include?: { [key in keyof Studycodemodel.Iquestion]: any };
  index?: keyof Studycodemodel.Imatchquestion;
  change: Function;
}>();

const emit = defineEmits<E>();
const formInline = reactive<Iobj<Studycodemodel.Iquestion>>({
  teamid: "",
  name: "",
  label: "",
  _offset: 0,
  range: "public",
});
type E = {
  (e: "change:questionid", value?: Studycodemodel.Iquestion[]): void;
  (event: "update:questionid", id: Studycodemodel.Iquestion[]): void;
};
const limit = 14;

const getquestion = computed(() => {
  return store.state.question?.rows || [];
});

const question = computed<Studycodemodel.Iquestion[]>({
  get() {
    return p.questionid;
  },
  set(v) {
    p.change(v);
    emit("update:questionid", v);
  },
});

defineExpose({
  questions: p.questionid,
});

watch(formInline, () => {
  debouncet1.value();
});

const getquestioncount = computed(() => {
  return store.state.question?.count || 0;
});
const drag = ref(false);

function currentchange(r: number) {
  formInline._offset = (r - 1) * limit;
}

const loading = ref(false);

const debouncet1 = ref(debouncet());
function debouncet() {
  return debounce(async () => {
    const { name, teamid, _offset } = formInline;
    const obj: Iobj<Studycodemodel.Iquestion> = {
      _order: "ID",
      _offset,
      _limit: limit,
    };
    let _like: [keyof Studycodemodel.Iquestion, any];
    if (name) {
      _like = ["name", formInline.name];
      const id = Number(name);
      if (id == name) {
        _like = ["ID", id];
      }
      obj._like = _like;
    }
    let t;
    let u;
    if (formInline.range == "team") {
      obj.teamid = teamId.value;
    } else if (formInline.range == "user") {
      obj.userid = user.value.ID;
    } else {
      obj.range = formInline.range;
    }
    if (setlabel.value && setlabel.value.length) {
      const data = store.state.label?.rows.filter((e) => e.type === "题目标签");
      const questionlabel = flatten(
        findpid(data ? data : [], setlabel.value[setlabel.value.length - 1])
      ).map((e) => e.ID);
      if (!obj._include) obj._include = {};
      obj._include.questionlabel = [
        "labelid",
        questionlabel.concat(setlabel.value[setlabel.value.length - 1]),
      ];
    }
    if (p._include) {
      Object.assign(obj, {
        _include: {
          ...(obj._include || {}),
          ...p._include,
        },
      });
    }
    loading.value = true;
    await store.dispatch("actionquestion", obj);
    loading.value = false;
  }, 300);
}
const grouplabel = computed(() => {
  const data = store.state.label?.rows.filter((e) => e.type === "题目标签");
  return findpid(data ? data : []);
});

const setlabel = ref<number[]>([]);

watch(
  () => setlabel.value,
  () => {
    debouncet1.value();
  }
);

onMounted(() => {
  debouncet1.value();
});
</script>

<style scoped>
.ant-bg {
  border-radius: 4px;
  padding-left: 36px;
  padding-right: 36px;
}

.col-left {
  height: 924.99px;
  background: #ffffff;
  border: 1px solid #d9d9d9;
  box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
    0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
  border-radius: 4px;
  padding: 10px;
  /* margin-right: 6px; */
}

.col-right {
  height: 924.99px;
  background: #ffffff;
  border: 1px solid #d9d9d9;
  box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
    0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
  border-radius: 4px;
  padding: 10px;
  /* margin-left: 6px; */
}

.mydata {
  height: 690px;
  overflow-y: auto;
  overflow-x: hidden;
}

.mydata::-webkit-scrollbar {
  width: 0px;
  height: 1px;
}

.mydata::-webkit-scrollbar-thumb {
  border-radius: 3px;
  box-shadow: inset 0 0 5px rgba(0, 0, 255, 0.3);
  background: #535353;
}

.mydata::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px rgba(0, 0, 255, 0.3);
  border-radius: 3px;
  background: #ededed;
}

.input {
  display: inline-block;
  width: 45%;
}

.col-center div {
  width: 90px;
}

.container-fluid .row {
  margin-bottom: 12px;
}

.icon-class-var {
  display: none;
}

.list {
  padding-bottom: 6px;
}

.list:hover {
  color: var(--color-cheng);
  background-color: #f8f8f8;
}

.list:hover .icon-class-var {
  display: inline-block;
}

.row {
  transition: all 0.4s;
}

.pager {
  float: right;
  margin-top: 5px;
}
</style>

<style>
.mydata .el-checkbox__label {
  display: none;
}

.sortable-chosen {
  background-color: #000 !important;
  color: #fff;
}
</style>
